// src/stores/userInfo.js
import { defineStore } from 'pinia'
import {
  listAllUserInfoAPI,
  addUserInfoAPI,
  updateUserInfoAPI,
  deleteUserInfoAPI,
  getUserInfoAPI,
  toggleUserInfoStatusAPI,
  searchUserInfoByNameAPI
} from '@/api/userInfoAPI'

export const useUserInfoStore = defineStore('userInfo', {
  state: () => ({
    users: [],
    total: 0,
    currentPage: 1,
    pageSize: 10,
    loading: false,
    selectedUser: null
  }),

  actions: {
    // 获取所有用户
    async fetchUsers() {
      this.loading = true
      try {
        const res = await listAllUserInfoAPI()
        
        if (res && (res.code === 0 || res.code === 200) && res.data) {
          // 后端返回的是 List<UserInfoDTO>
          if (Array.isArray(res.data)) {
            this.users = res.data
            this.total = res.data.length
          } else {
            this.users = []
            this.total = 0
          }
        } else {
          console.error('获取用户列表失败:', res?.message || '未知错误')
          this.users = []
          this.total = 0
        }
      } catch (error) {
        console.error('获取用户失败:', error)
        this.users = []
        this.total = 0
      } finally {
        this.loading = false
      }
    },

    // 根据用户名搜索用户
    async searchUsersByName(name) {
      this.loading = true
      try {
        const res = await searchUserInfoByNameAPI(name)

        if (res && (res.code === 0 || res.code === 200) && res.data) {
          if (Array.isArray(res.data)) {
            this.users = res.data
            this.total = res.data.length
          } else {
            this.users = []
            this.total = 0
          }
        } else {
          console.error('搜索用户失败:', res?.message || '未知错误')
          this.users = []
          this.total = 0
        }
      } catch (error) {
        console.error('搜索用户失败:', error)
        this.users = []
        this.total = 0
      } finally {
        this.loading = false
      }
    },

    // 新增用户
    async addUser(userData) {
      try {
        const res = await addUserInfoAPI(userData)
        if (res && (res.code === 0 || res.code === 200)) {
          await this.fetchUsers()
          return { success: true }
        } else {
          throw new Error(res?.message || '添加用户失败')
        }
      } catch (error) {
        console.error('新增用户失败:', error)
        throw error
      }
    },

    // 编辑用户
    async updateUser(id, userData) {
      try {
        const res = await updateUserInfoAPI(id, userData)
        if (res && (res.code === 0 || res.code === 200)) {
          await this.fetchUsers()
          return { success: true }
        } else {
          throw new Error(res?.message || '更新用户失败')
        }
      } catch (error) {
        console.error('更新用户失败:', error)
        throw error
      }
    },

    // 删除用户
    async deleteUser(id) {
      try {
        const res = await deleteUserInfoAPI(id)
        if (res && (res.code === 0 || res.code === 200)) {
          await this.fetchUsers()
          return { success: true }
        } else {
          throw new Error(res?.message || '删除用户失败')
        }
      } catch (error) {
        console.error('删除用户失败:', error)
        throw error
      }
    },

    // 获取单个用户详情
    async getUserById(id) {
      try {
        const res = await getUserInfoAPI(id)
        if (res && (res.code === 0 || res.code === 200) && res.data) {
          this.selectedUser = res.data
          return res.data
        } else {
          throw new Error(res?.message || '获取用户详情失败')
        }
      } catch (error) {
        console.error('获取用户详情失败:', error)
        throw error
      }
    },

    // 切换用户状态
    async toggleUserStatus(id) {
      try {
        const res = await toggleUserInfoStatusAPI(id)
        if (res && (res.code === 0 || res.code === 200)) {
          await this.fetchUsers()
          return { success: true }
        } else {
          throw new Error(res?.message || '切换用户状态失败')
        }
      } catch (error) {
        console.error('切换用户状态失败:', error)
        throw error
      }
    }
  }
})